
<template>
  <h2>数据详情: </h2>
  <a-button type="primary" @click="toImageFilesTablePage">
    查看&nbsp;{{this.$route.query.experiment_name}}&nbsp;实验下其他文件
  </a-button>
  <a-divider
      type="horizontal"
      :style="{ borderColor: '#19a7ff', borderWidth: '2px' }"
  />

  <a-table :columns="imageTableColumns" :data-source="Data" :pagination="false" :scroll="{ y: '70vh' }">
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'action'">
        <span>
          <a @click="handleClickPic(record)">查看</a>
          <a-divider type="vertical" />
        </span>
      </template>
    </template>
  </a-table>
</template>


<script>
import axiosInstance from "@/axios/axios.js";
import TIFF from 'tiff.js';
export default {
  name: "Image",
  data() {
    return {
      Data: [],
      imageTableColumns: [
        {
          title: "文件名",
          dataIndex: "name",
          key: "name"
        },
        {
          title: "操作",
          key: "action",
          scopedSlots: { customRender: "action" }
        }
      ]
    };
  },
  created() {
    this.initImageData();
  },
  methods: {
    initImageData() {
      axiosInstance({
        method: "POST",
        url: "/myData/getImages",
        headers: {
          Authorization: `Bearer ${this.$cookies.get("jwt")}` // 设置请求头，携带 JWT
        },
        data: {
          username: this.$cookies.get("username"),
          userAddress: this.$cookies.get("userAddress"),
          userSecret: this.$cookies.get("userSecret"),
          dataId: this.$route.query.experiment_id,
          experimentSetName: this.$route.query.experiment_set_name,
          batchName: this.$route.query.experiment_batch_name,
          experimentName: this.$route.query.experiment_name,
        },
      })
          .then((response) => {
            console.log("images", response.data);
            this.Data = response.data.data.images;
            var imagesPath = response.data.data.url;

            this.Data = this.Data.map(item => {
              item.imgUrl = imagesPath + item.name;
              return item;
            });

            console.log("this.Data=", this.Data);
          })
          .catch((err) => {
            console.log(err);
          });
    },

    async handleClickPic(image) {
      console.log("image", image);

      // 处理 TIFF 文件转换
      if (image.imgUrl.endsWith('.tif')) {
        try {
          const response = await fetch(image.imgUrl);
          if (!response.ok) {
            console.error('Failed to load TIF image:', response.statusText);
            return;
          }
          const buffer = await response.arrayBuffer();
          const tiff = new Tiff({ buffer });
          const canvas = document.createElement('canvas');
          const ctx = canvas.getContext('2d');
          const width = tiff.width();
          const height = tiff.height();
          canvas.width = width;
          canvas.height = height;
          const imageData = tiff.toCanvas();
          ctx.drawImage(imageData, 0, 0, width, height);
          const pngUrl = canvas.toDataURL();

          this.$router.push({
            path: '/detail',
            query: {
              imgUrl: pngUrl, // 传递临时 PNG URL
              originalImgUrl: image.imgUrl, // 保留原始 TIFF URL
              experimentSetId: image.experiment_set_id,
              batchId: image.batch_id,
              experimentId: image.experiment_id,
              hash: image.tx_hash,
            }
          });
        } catch (error) {
          console.error('Error loading TIF image:', error);
        }
      } else {
        this.$router.push({
          path: '/detail',
          query: {
            imgUrl: image.imgUrl,
            originalImgUrl: image.imgUrl,
            experimentSetId: image.experiment_set_id,
            batchId: image.batch_id,
            experimentId: image.experiment_id,
            hash: image.tx_hash,
          }
        });
      }
    },

    toImageFilesTablePage() {
      this.$router.push({
        path: '/MyData/ImageFilesTable',
        query: {
          experiment_set_name: this.$route.query.experiment_set_name,
          experiment_batch_name: this.$route.query.experiment_batch_name,
          experiment_name: this.$route.query.experiment_name,
        }
      });
    },
  },
};
</script>


<style scoped>
.scroll-container {
  max-width: 90vw; /* Adjust the max width as per your requirement */
  margin: auto; /* This will center the container */
  max-height: 70vh; /* 设置一个最小高度 */
  overflow-y: auto; /* 允许在垂直方向上滚动 */
}

.image-container {
  max-width:90%; /* This will make sure the image container takes the full width of the column */
  padding: 0 0 8px 10px; /* Add some padding around the images */
}

.image-style{
  max-width: 100%; /* This will make sure the image is responsive and scales down */
  max-height: 100px; /* This will limit the image height and maintain aspect ratio */
  display: block; /* To remove bottom space under the image */
  margin: auto; /* Center the image horizontally */
}

/* Responsive adjustments */
@media (max-width: 768px) {
  .image-container .a-image {
    max-height: 150px; /* Smaller height for smaller screens */
  }
}

@media (max-width: 480px) {
  .image-container .a-image {
    max-height: 100px; /* Even smaller height for mobile screens */
  }
}
</style>